package com.kevin.permission.service;

import com.google.common.base.Preconditions;
import com.kevin.permission.common.RequestHolder;
import com.kevin.permission.dao.SysDeptMapper;
import com.kevin.permission.dao.SysUserMapper;
import com.kevin.permission.exception.ParamsException;
import com.kevin.permission.model.SysDept;
import com.kevin.permission.param.DeptParam;
import com.kevin.permission.util.BeanValidator;
import com.kevin.permission.util.IpUtil;
import com.kevin.permission.util.LevelUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysLogService sysLogService;

    public void save(DeptParam param){
        BeanValidator.check(param);
        if (checkExist(param.getParentId(),param.getName(),param.getId())){
            throw new ParamsException("同一层级下不存在相同名称的部门");
        }
        SysDept dept=SysDept.builder().name(param.getName()).parentId(param.getParentId())
                .seq(param.getSeq()).remark(param.getRemark()).build();
        dept.setLevel(LevelUtil.calculateLevel(getLevel(param.getParentId()),param.getParentId()));
        dept.setOperator(RequestHolder.getCurrentUser().getUsername());
        dept.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        dept.setOperatorTime(new Date());
        sysDeptMapper.insertSelective(dept);

        sysLogService.saveDeptLog(null,dept);
    }

    public void update(DeptParam param){
        BeanValidator.check(param);
        if (checkExist(param.getParentId(),param.getName(),param.getId())){
            throw new ParamsException("同一层级下不存在相同名称的部门");
        }
        SysDept before=sysDeptMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before,"待更新部门不存在");

        SysDept after=SysDept.builder().id(param.getId()).name(param.getName()).parentId(param.getParentId())
                .seq(param.getSeq()).remark(param.getRemark()).build();
        after.setLevel(LevelUtil.calculateLevel(getLevel(param.getParentId()),param.getParentId()));
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperatorTime(new Date());

        updateWithChild(before,after);
        sysLogService.saveDeptLog(before,after);
    }

    private void updateWithChild(SysDept before, SysDept after) {
        String newLevelPrefix=after.getLevel();
        String oldLevelPrefix=before.getLevel();
        if (!after.getLevel().equals(before.getLevel())){
            List<SysDept> deptList=sysDeptMapper.getChildDeptListByLevel(before.getLevel());
            if (CollectionUtils.isNotEmpty(deptList)){
                for (SysDept dept :deptList){
                    String level=dept.getLevel();
                    if (level.indexOf(oldLevelPrefix)==0){
                        level=newLevelPrefix+level.substring(oldLevelPrefix.length());
                        dept.setLevel(level);
                    }
                }
                sysDeptMapper.batchUpdateLevel(deptList);
            }
        }
        sysDeptMapper.updateByPrimaryKey(after);
    }

    public void delete(int deptId){
        SysDept dept=sysDeptMapper.selectByPrimaryKey(deptId);
        Preconditions.checkNotNull(dept,"待删除部门不能为空，无法删除");
        if (sysDeptMapper.countByParentId(dept.getId())>0){
            throw new ParamsException("当前部门下面有子部门，无法删除");
        }
         //FIXME 删除部门时，部门下面有人要
        if(sysUserMapper.countByDeptId(dept.getId()) > 0) {
            throw new ParamsException("当前部门下面有用户，无法删除");
        }
        sysDeptMapper.deleteByPrimaryKey(deptId);
    }

    private boolean checkExist(Integer parentId, String deptName, Integer deptId) {
        return sysDeptMapper.countByNameAndParentId(parentId,deptName,deptId)>0;
    }

    private String getLevel(Integer parentId) {
        SysDept sysDept=sysDeptMapper.selectByPrimaryKey(parentId);
        if (sysDept==null){
            return null;
        }
        return sysDept.getLevel();
    }
}
